package com.itfreer.gis.server.mercator;

import org.geotools.geometry.jts.ReferencedEnvelope;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.ParseException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;

/**
 * 切片辅助类
 */
public class TileUtils {

	/**
	 * 将行列号转换为polygon对象
	 * 
	 * @param x
	 * @param y
	 * @param z
	 * @return
	 */
	public static String parseXyz2Bound(int x, int y, int z) {
		StringBuilder sb = new StringBuilder("POLYGON ((");
		double lngLeft = MercatorProjection.tileXToLongitude(x, z) - 0.00105;
		double latUp = MercatorProjection.tileYToLatitude(y, z) + 0.00105;
		double lngRight = MercatorProjection.tileXToLongitude(x + 1, z) + 0.00105;
		double latDown = MercatorProjection.tileYToLatitude(y + 1, z) - 0.00105;
		sb.append(lngLeft + " " + latUp + ", ");
		sb.append(lngRight + " " + latUp + ", ");
		sb.append(lngRight + " " + latDown + ", ");
		sb.append(lngLeft + " " + latDown + ", ");
		sb.append(lngLeft + " " + latUp + ")) ");
		return sb.toString();
	}

	/**
	 * 将行列号转换为polygon对象
	 * 
	 * @param x
	 * @param y
	 * @param z
	 * @return
	 * @throws ParseException 
	 */
	public static ReferencedEnvelope parseXyz2Bound(int x, int y, int z, CoordinateReferenceSystem sourceCrs) {
		double lngLeft = MercatorProjection.tileXToLongitude(x, z) - 0.00105;
		double latUp = MercatorProjection.tileYToLatitude(y, z) + 0.00105;
		double lngRight = MercatorProjection.tileXToLongitude(x + 1, z) + 0.00105;
		double latDown = MercatorProjection.tileYToLatitude(y + 1, z) - 0.00105;
		return new ReferencedEnvelope(lngLeft, lngRight, latUp, latDown, sourceCrs);
	}

	/**
	 * 转换为平面坐标
	 * 
	 * @param x
	 * @param y
	 * @param z
	 * @param geom
	 */
	public static void convert2Piexl(int x, int y, int z, Geometry geom) {
		double px = MercatorProjection.tileXToPixelX(x);
		double py = MercatorProjection.tileYToPixelY(y);
		Coordinate[] cs = geom.getCoordinates();
		byte zoom = (byte) z;
		for (Coordinate c : cs) {
			c.x = (int) (((MercatorProjection.longitudeToPixelX(c.x, zoom)) - px) * 16);
			c.y = (int) (((MercatorProjection.latitudeToPixelY(c.y, zoom)) - py) * 16);
		}
	}

}
